package com.lhh.myspringboot.service.impl;


import com.alibaba.fastjson.JSON;
import com.lhh.myspringboot.bean.Content;
import com.lhh.myspringboot.service.ContentService;
import com.lhh.myspringboot.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class ContentServiceImpl implements ContentService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;


    // 1.解析数据放入es中
    public Boolean parseDataAndPutES(String keywords) throws IOException {

        ArrayList<Content> contents = HtmlParseUtil.parseJD(keywords);

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2s");
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }

        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulkItemResponses.hasFailures();

    }

    // 2. 获取这些数据实现搜索功能
    public List<Map<String, Object>> searchPage(String keywords, int pafeNo, int pageSize) throws IOException {
        if (pafeNo <= 1){
            pafeNo = 1;
        }

        // 条件查询
        SearchRequest searchRequest = new SearchRequest("jd_goods");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 分页
        searchSourceBuilder.from(pafeNo);
        searchSourceBuilder.size(pageSize);

         // 精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("tittle", keywords);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(6, TimeUnit.SECONDS));

         // 高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("tittle");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        // 执行搜索
         searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit: hits) {
            // 高亮处理  先获取高亮的字段， 再替换
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("tittle");

            Map<String, Object> sourceMap = hit.getSourceAsMap();

            if (title!=null){
                Text[] fragments = title.fragments();

                StringBuilder highTitle = new StringBuilder("");

                for (Text text: fragments) {
                    highTitle.append(text);
                }
                sourceMap.put("title",highTitle);  // 替换
            }
            list.add(sourceMap);
        }

        return list;


    }
}
